<?php

App::uses('AppController', 'Controller');

/**
 * Profiles Controller
 *
 * @property Profile $Profile
 * @property PaginatorComponent $Paginator
 */
class ProfilesController extends AppController
{
    /**
     * Components
     *
     * @var array
     */

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {
        if ($this->Session->check('Auth.User'))
        {
            $user = $this->Auth->user();
            $sql = "SELECT * FROM tb_profiles AS User WHERE users_id = {$user['id']}";
            $this->set('user', $this->Profile->query($sql));
            //debug($this->Profile->query($sql));
        } else
        {
            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }

    public function isAuthorized($user)
    {
        if (in_array($this->action, array('edit', 'delete', 'avatar')))
        {
            if ($user['id'] != $this->request->params['pass'][0])
            {
                return false;
            }
        }
        return true;
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null)
    {
        if (!$this->Profile->exists($id))
        {
            throw new NotFoundException(__('Invalid profile'));
        }

        $options = array('conditions' => array('Profile.' . $this->Profile->primaryKey => $id));
        $this->set('profile', $this->Profile->find('first', $options));
        //debug($this->Profile->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        if ($this->request->is('post'))
        {
            $this->Profile->create();
            if ($this->Profile->save($this->request->data))
            {
                $this->Session->setFlash(__('The profile has been saved.'), 'alert-success');
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The profile could not be saved. Please, try again.'), 'alert-danger');
            }
        }
        $users = $this->Profile->User->find('list');
        $this->set(compact('users'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null)
    {
        if (!$this->Profile->exists($id))
        {
            throw new NotFoundException(__('Invalid profile'));
        }
        if ($this->request->is(array('post', 'put')))
        {
            $profile = $this->request->data;
            $name = $profile['Profile']['name'];
            $gender = $profile['Profile']['gender'];
            $address = $profile['Profile']['address'];
            $phone = $profile['Profile']['phone'];
            $birthday = $profile['Profile']['birthday'];
            $userId = $this->Auth->user('id');

            $sql = "UPDATE tb_profiles SET name = '{$name}',gender = '{$gender}', address = '{$address}', phone = '{$phone}', birthday = '{$birthday}', updated = NOW() WHERE users_id = {$userId}";

            $this->Profile->query($sql);
            $this->Session->setFlash(__('The profile has been saved.'), 'alert-success');
            return $this->redirect(array('action' => 'view', $userId));
        } else
        {
            $options = array('conditions' => array('Profile.' . $this->Profile->primaryKey => $id));
            $this->request->data = $this->Profile->find('first', $options);
        }
        //$users = $this->Profile->User->find('all');
        $this->set(compact('users'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null)
    {
        $this->Profile->id = $id;
        if (!$this->Profile->exists())
        {
            throw new NotFoundException(__('Invalid profile'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Profile->delete())
        {
            $this->Session->setFlash(__('The profile has been deleted.'), 'alert-success');
        } else
        {
            $this->Session->setFlash(__('The profile could not be deleted. Please, try again.'), 'alert-danger');
        }
        return $this->redirect(array('action' => 'index'));
    }

    /**
     * avatar method upload avatar
     * @param int id
     * @return void
     */

    public function avatar($id = null)
    {
        //Get image
        if ($this->request->is('post'))
        {
            $file = $this->request->data['Profile']['image'];
            $userId = $this->Auth->user('id');
            //set allowed extensions
            $arr_ext = array('jpg', 'jpeg', 'gif', 'png');
            //explode name 
            $name = explode('.', strtolower($file['name']));
            //Encript name
            $fileName = uniqid($name[0]);
            //File extention
            $ext = $name[1];
            $size = floor($file['size'] / 1024); //size kb
            $name_fix = $fileName . "." . $ext;

            //Validate and upload image
            if (in_array($ext, $arr_ext) and ($size < 2 * 2048))
            {
                if (move_uploaded_file($file['tmp_name'], WWW_ROOT . 'uploads/' . $name_fix))
                {
                    $avatar = $name_fix;
                } else
                {
                    $avatar = 'no-avatar.jpg';
                }
            }

            //Update profile
            $data = array('Profile' => array('users_id' => $userId, 'avatar' => $avatar));
            if ($this->Profile->save($data))
            {
                $this->Session->setFlash(__('The avatar has been updated.'), 'alert-success');
                return $this->redirect(array('action' => 'view', $userId));
            } else
            {
                $this->Session->setFlash(__('The profile could not be updated. Please, try again.'), 'alert-danger');
            }
        }
    }

}
